package com.atguigu.java8.lambda;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class TestLambda4 {

    // Consumer<T>：消费型接口
    // 	核心方法：void accept(T t)
    @Test
    public void test1() {
        happy(10000, x -> System.out.println("shopping cost:" + x));
    }

    private void happy(double money, Consumer<Double> consumer) {
        consumer.accept(money);
    }

    // Supplier<T>：供给型接口
    // 核心方法：T get()
    @Test
    public void test2() {
        List<Integer> numList = getNumList(10, () -> (int) (Math.random() * 100));
        System.out.println(numList);
    }

    // 需求：产生指定个数的整数，并放入集合中
    private List<Integer> getNumList(int num, Supplier<Integer> supplier) {
        List<Integer> numList = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            numList.add(supplier.get());
        }

        return numList;
    }

    // Function<T,R>：函数型接口
    // 核心方法：R apply(T t)
    @Test
    public void test3() {
        String result = strHandle("\t\t\t Lambda Expression", str -> str.trim());
        System.out.println(result);

        result = strHandle("lambda", str -> str.substring(1, 3));
        System.out.println(result);
    }

    // 需求：用于处理字符串
    private String strHandle(String value, Function<String, String> function) {
        return function.apply(value);
    }

    // Predicate<T>：断言型接口
    // 核心方法：boolean test(T t)
    @Test
    public void test4() {
        List<String> stringList = Arrays.asList("lambda", "ok", "expression", "we", "bus");
        List<String> filteredList = strFilter(stringList, x -> x.length() >= 3);
        System.out.println(filteredList);
    }

    // 需求：将满足条件的字符串，加入到集合中
    private List<String> strFilter(List<String> stringList, Predicate<String> predicate) {
        List<String> resultList = new ArrayList<>();

        for (String string : stringList) {
            if (predicate.test(string)) {
                resultList.add(string);
            }
        }
        return resultList;
    }

}
